package com.best4cloud.user.web.rest;

import com.best4cloud.user.domain.SysMenu;
import com.best4cloud.user.domain.SysRole;
import com.best4cloud.user.domain.SysUser;
import com.best4cloud.user.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collection;
import java.util.Set;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/auth")
public class AuthResource {

    @Autowired
    private SysUserService sysUserService;

    @GetMapping("/loadUserByUsername")
    public UserDetails loadUserByUsername(@RequestParam("username") String username) {
        SysUser sysUser = sysUserService.getUserByUsername(username);
        if (sysUser == null) {
            return null;
        }
        String[] permissions = sysUser.getRoles()
                .stream()
                .map(SysRole::getMenus)
                .flatMap(Collection::stream)
                .map(SysMenu::getPermission).toArray(String[]::new);
        return User.builder().username(username).password(sysUser.getPassword()).authorities(permissions).build();
    }
}
